package com.lzm.ydpt.module.mall.dialog;

import android.content.Context;
import android.graphics.Paint;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.byt.framlib.commonutils.ToastUitl;
import com.byt.framlib.commonutils.image.ImageLoaderUtils;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.GoodsOption;
import com.lzm.ydpt.entity.mall.ShopGoods;
import com.lzm.ydpt.entity.mall.SpecBean;
import com.lzm.ydpt.module.mall.adapter.GoodsAttrsAdapter;
import com.lzm.ydpt.module.mall.adapter.ISku;
import com.lzm.ydpt.module.mall.utils.BigValueFilter;
import com.lzm.ydpt.module.mall.utils.ProductUtil;

public class SkuBottomDialog extends BottomSheetDialog {
    private GoodsOption mGoodsOption;
    private Context mContext;
    private SureClickCall mSureClickCall;
    private ImageView rcimg_dia_pic;
    private ImageView img_dismiss;
    private TextView tv_product_coin;
    private TextView product_current_price;
    private TextView tv_old_price;
    private TextView tv_product_stock;
    private ImageView tv_sku_num_add;
    private EditText edt_sku_num_data;
    private ImageView tv_sku_num_sub;
    private RecyclerView rv_sku_list;
    private TextView tv_commit_order;
    private TextView tv_add_cart;
    private TextView tv_submit_order;
    private int mType = 0; // 0是商城选择sku 有加入购物车和立即购买 1是礼品sku 有加入购物车和立即兑换 2 只有确定是添加 3只有确定是兑换或者是购买
    private SpecBean[] selectedValue;   //选中的属性
    private ShopGoods selectGoods;
    private BigValueFilter tempInputFilter = null;

    public SkuBottomDialog(Context context, GoodsOption goodsOption, ShopGoods shopGoods, SureClickCall sureClickCall) {
        super(context);
        this.mGoodsOption = goodsOption;
        this.mContext = context;
        this.mSureClickCall = sureClickCall;
        this.selectGoods = shopGoods;
        if (selectGoods != null) {
            int size = mGoodsOption.getSpecs().size();
            selectedValue = new SpecBean[size];
            String[] specIds = selectGoods.getSpec_ids().split(",");
            for (int i = 0; i < size; i++) {
                for (SpecBean specBean : mGoodsOption.getSpecs().get(i).getItems()) {
                    if (specIds[i].equals(specBean.getSpec_id() + "")) {
                        selectedValue[i] = specBean;
                    }
                }
            }
        } else {
            int sizeOption = mGoodsOption.getSpecs().size();
            if (sizeOption == 1) {
                selectedValue = new SpecBean[sizeOption];
                int sizef = mGoodsOption.getSpecs().get(0).getItems().size();
                if (sizef == 1) {
                    selectGoods = mGoodsOption.getOptions().get(0);
                    selectedValue[0] = mGoodsOption.getSpecs().get(0).getItems().get(0);
                }
            }
        }
        initView();
    }

    /**
     * @param type 0 智慧商城 1礼品商城 2的话是单个的确定就是点击加入购物车 3 单个确认购买
     */
    public void showDialog(int type) {
        this.mType = type;
        showView();
        show();
    }

    public void setDefaultData(String imgSrc, String min_price, String max_price, int min_glod, int max_glod, String min_market_price, String max_market_price, int coin, int stock) {
        ImageLoaderUtils.display(rcimg_dia_pic, imgSrc);
        StringBuffer sb = new StringBuffer();
        if (min_glod > 0) {
            sb.append(min_glod + "金币");
        }
        if (max_glod > 0 && max_glod != min_glod) {
            sb.append("~" + max_glod + "金币");
        }
        if (ProductUtil.pausePrice(min_price) > 0) {
            if (!TextUtils.isEmpty(sb.toString())) {
                sb.append("+¥" + min_price);
            } else {
                sb.append("¥" + min_price);
            }
        }
        if (ProductUtil.pausePrice(max_price) > 0 && !max_price.equals(min_price)) {
            sb.append("~¥" + max_price);
        }
        product_current_price.setText(sb.toString());

        if (ProductUtil.pausePrice(min_market_price) > 0) {
            if (!min_market_price.equals(max_market_price)) {
                tv_old_price.setText("¥" + min_market_price + "~¥" + max_market_price);
            } else {
                tv_old_price.setText("¥" + min_market_price);
            }
            tv_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
            tv_old_price.setVisibility(View.VISIBLE);
        } else {
            tv_old_price.setVisibility(View.GONE);
        }
        tv_product_stock.setText("库存:" + stock);
        if (coin > 0) {
            tv_product_coin.setVisibility(View.VISIBLE);
            tv_product_coin.setText("赠送" + coin + "金币");
        } else {
            tv_product_coin.setVisibility(View.GONE);
        }
        edt_sku_num_data.setText(String.valueOf(1));
        edt_sku_num_data.setSelection(edt_sku_num_data.getText().length());
    }

    private void setViewData() {
        product_current_price.setText("¥" + selectGoods.getPrice_rmb());
        if (ProductUtil.pausePrice(selectGoods.getMarket_price()) > 0) {
            tv_old_price.setText("¥" + selectGoods.getMarket_price());
            tv_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
            tv_old_price.setVisibility(View.VISIBLE);
        } else {
            tv_old_price.setVisibility(View.GONE);
        }
        ImageLoaderUtils.display(rcimg_dia_pic, selectGoods.getImage_src());
        tv_product_stock.setText("库存:" + selectGoods.getInventory());
        if (tempInputFilter == null) {
            tempInputFilter = new BigValueFilter();
        }
        tempInputFilter.setMaxValue(selectGoods.getInventory());
        if (selectGoods.getGold() > 0) {
            tv_product_coin.setVisibility(View.VISIBLE);
            tv_product_coin.setText("赠送" + selectGoods.getGold() + "金币");
        } else {
            tv_product_coin.setVisibility(View.GONE);
        }
        if (selectGoods.getTotal() == 0) {
            edt_sku_num_data.setText(String.valueOf(1));
        } else {
            edt_sku_num_data.setText(String.valueOf(selectGoods.getTotal()));
        }
        edt_sku_num_data.setSelection(edt_sku_num_data.length());
    }

    private void showView() {
        switch (mType) {
            case 0:
                tv_commit_order.setVisibility(View.GONE);
                tv_add_cart.setVisibility(View.VISIBLE);
                tv_submit_order.setVisibility(View.VISIBLE);
                tv_submit_order.setText("立即购买");
                break;
            case 1:
                tv_commit_order.setVisibility(View.GONE);
                tv_add_cart.setVisibility(View.VISIBLE);
                tv_submit_order.setVisibility(View.VISIBLE);
                tv_submit_order.setText("立即兑换");
                break;
            default:
                tv_commit_order.setVisibility(View.VISIBLE);
                tv_add_cart.setVisibility(View.GONE);
                tv_submit_order.setVisibility(View.GONE);
                break;
        }
    }

    private void initView() {
        View view = getLayoutInflater().inflate(R.layout.mall_product_sku_sheet, null);
        rcimg_dia_pic = view.findViewById(R.id.rcimg_dia_pic);
        img_dismiss = view.findViewById(R.id.img_sku_dismiss);
        img_dismiss.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                dismiss();
            }
        });
        tv_product_coin = view.findViewById(R.id.tv_product_coin);
        product_current_price = view.findViewById(R.id.tv_current_price);
        tv_old_price = view.findViewById(R.id.tv_old_price);
        tv_product_stock = view.findViewById(R.id.tv_product_stock);
        tv_sku_num_add = view.findViewById(R.id.tv_sku_num_add);
        edt_sku_num_data = view.findViewById(R.id.edt_sku_num_data);
        tempInputFilter = new BigValueFilter();
        edt_sku_num_data.setFilters(new InputFilter[]{tempInputFilter});
        tv_sku_num_sub = view.findViewById(R.id.tv_sku_num_sub);
        tv_sku_num_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = 1;
                try {
                    num = Integer.parseInt(edt_sku_num_data.getText().toString());
                } catch (Exception e) {
                    num = 1;
                }
                if (selectGoods != null) {
                    if (num >= selectGoods.getInventory()) {
                        ToastUitl.showShort("购买该商品不能超过" + selectGoods.getInventory() + "哦");
                        return;
                    }
                }
                num++;
                edt_sku_num_data.setText(String.valueOf(num));
                edt_sku_num_data.setSelection(edt_sku_num_data.getText().length());
            }
        });
        tv_sku_num_sub = view.findViewById(R.id.tv_sku_num_sub);
        tv_sku_num_sub.setOnClickListener(v -> {
            int num = 1;
            try {
                num = Integer.parseInt(edt_sku_num_data.getText().toString());
            } catch (Exception e) {
                num = 1;
            }
            if (num <= 1) {
                ToastUitl.showShort("购买该商品不能低于1哦");
                return;
            }
            num--;
            edt_sku_num_data.setText(String.valueOf(num));
            edt_sku_num_data.setSelection(edt_sku_num_data.getText().length());
        });
        tv_commit_order = view.findViewById(R.id.tv_commit_order);
        tv_commit_order.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (mSureClickCall != null) {
                    if (!isAll()) {
                        return;
                    }
                    int tempNum = 1;
                    try {
                        tempNum = Integer.parseInt(edt_sku_num_data.getText().toString());
                    } catch (Exception e) {
                        tempNum = 1;
                    }
                    if (selectGoods != null) {
                        if (tempNum > selectGoods.getInventory()) {
                            ToastUitl.showShort("该商品库存不足,不能超过" + selectGoods.getInventory() + "哦");
                            return;
                        }
                    }
                    if (mType == 2) {
                        mSureClickCall.onAddCartClick(selectedValue, tempNum);
                    } else {
                        mSureClickCall.onSubmitOrderClick(selectedValue, tempNum);
                    }
                }
            }
        });
        tv_add_cart = view.findViewById(R.id.tv_add_cart);
        tv_add_cart.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (mSureClickCall != null) {
                    if (!isAll()) {
                        return;
                    }
                    int tempNum = 1;
                    try {
                        tempNum = Integer.parseInt(edt_sku_num_data.getText().toString());
                    } catch (Exception e) {
                        tempNum = 1;
                    }
                    if (selectGoods != null) {
                        if (tempNum > selectGoods.getInventory()) {
                            ToastUitl.showShort("该商品库存不足,不能超过" + selectGoods.getInventory() + "哦");
                            return;
                        }
                    }
                    mSureClickCall.onAddCartClick(selectedValue, tempNum);
                }
            }
        });
        tv_submit_order = view.findViewById(R.id.tv_submit_order);
        tv_submit_order.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (mSureClickCall != null) {
                    if (!isAll()) {
                        return;
                    }
                    int tempNum = 1;
                    try {
                        tempNum = Integer.parseInt(edt_sku_num_data.getText().toString());
                    } catch (Exception e) {
                        tempNum = 1;
                    }
                    if (selectGoods != null) {
                        if (tempNum > selectGoods.getInventory()) {
                            ToastUitl.showShort("该商品库存不足,不能超过" + selectGoods.getInventory() + "哦");
                            return;
                        }
                    }
                    mSureClickCall.onSubmitOrderClick(selectedValue, tempNum);
                }
            }
        });
        rv_sku_list = view.findViewById(R.id.rv_sku_list);
        GoodsAttrsAdapter mAdapter = new GoodsAttrsAdapter(mContext, mGoodsOption.getSpecs(), mGoodsOption.getOptions());
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_sku_list.setLayoutManager(layoutManager);
        rv_sku_list.setFocusable(false);
        mAdapter.setSKUInterface(new ISku() {
            @Override
            public void selectedAttribute(SpecBean[] attr) {
                selectedValue = attr;
                if (isAllView()) {
                    getSelectGoods();
                    setViewData();
                }
            }

            @Override
            public void uncheckAttribute(SpecBean[] attr) {
                selectedValue = attr;
            }
        });
        if (selectGoods != null) {
            mAdapter.setSelect(selectGoods);
            setViewData();
        }
        rv_sku_list.setAdapter(mAdapter);
        setContentView(view);
        View parent = (View) view.getParent();//获取ParentView
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        view.measure(0, 0);
        behavior.setPeekHeight(view.getMeasuredHeight());
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) parent.getLayoutParams();
        params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        parent.setLayoutParams(params);
        setCancelable(false);
    }

    private boolean isAll() {
        if (selectedValue == null) {
            ToastUitl.showShort("请选择商品属性");
            return false;
        }
        if (selectGoods == null) {
            ToastUitl.showShort("请选择商品");
            return false;
        }
        if (Integer.parseInt(edt_sku_num_data.getText().toString()) <= 0) {
            ToastUitl.showShort("请选择商品数量");
            return false;
        }
        for (int i = 0, length = selectedValue.length; i < length; i++) {
            SpecBean specBean = selectedValue[i];
            if (specBean == null) {
                ToastUitl.showShort("请选择" + mGoodsOption.getSpecs().get(i).getSpec_name());
                return false;
            }
        }
        return true;
    }

    private boolean isAllView() {
        if (selectedValue == null) {
            return false;
        }
        for (int i = 0, length = selectedValue.length; i < length; i++) {
            SpecBean specBean = selectedValue[i];
            if (specBean == null) {
                return false;
            }
        }
        return true;
    }

    private void getSelectGoods() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = selectedValue.length; i < length; i++) {
            if (selectedValue[i] != null) {
                if (TextUtils.isEmpty(sb.toString())) {
                    sb.append(selectedValue[i].getSpec_id());
                } else {
                    sb.append("," + selectedValue[i].getSpec_id());
                }
            }
        }
        for (int i = 0; i < mGoodsOption.getOptions().size(); i++) {
            if (mGoodsOption.getOptions().get(i).getSpec_ids().equals(sb.toString())) {
                selectGoods = mGoodsOption.getOptions().get(i);
            }
        }
    }


    public interface SureClickCall {
        void onAddCartClick(SpecBean[] selectedValue, int num); // 加入购物车

        void onSubmitOrderClick(SpecBean[] selectedValue, int num);// 提交订单
    }
}